/**
 * @author Chris Wilcox
 * @author Preston Parrett
 * 
 * @date 2008/03/17
 * 
 * The Evolution program was written for UCSB's CS165b class.
 * 
 */

package evolution;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;

/**
 * The selector class (Inspired by 'Natural Selection' and 'Artificial Selection')
 * performs the actual breeding process.
 * 
 * @author cwilcox
 *
 */
public class Selector {
	/**
	 * Create a new Selector for life with the specified breedratio
	 * @param breedRatio the decimal number between 0 and 1 which specifies
	 * what portion of bred life to allow to breed.
	 */
	public Selector(float breedRatio) {
		breedRate = breedRatio;
	}
	
	private float breedRate;
	
	/**
	 * Calls the mate function on the fit members of the specified life.
	 * @param life the array of SexualReproducers to mate
	 * @return an new array of SexualReproducers containing most fit parents and their children
	 */
	public Consumer[] breed(Consumer[] life) {
		
		Arrays.sort(life);
		
		int breedNum = (int)(life.length*breedRate);
		
		Consumer[] newlife = new Consumer[life.length];
		Consumer[] children = new Consumer[life.length];
		
		for (int i=0; i<breedNum; i++) { //catch (IndexOutOfBoundsException e) {
			int j = i*2;
			
			newlife[i] = life[i];
			newlife[i+1] = life[i+1];
			
			Consumer[] theseKids = life[i].mate(life[i+1]);
			children[i] = theseKids[0];
			children[i+1] = theseKids[1];
		}
		/*
		Vector<Consumer> v = new Vector<Consumer>();
		
		for (int i=0; i<breedNum; i+=2) 
		{
			v.addElement(life[i]);
			v.addElement(life[i+1]);
		}*/
	

		for (int i=breedNum; i<life.length; i++) 
		{			
				newlife[i] = children[i-breedNum];
		}
		
		return newlife;
	}
	
	public int[] getScores(Consumer[] cons) {
		int[] scores = new int[cons.length];
		for (int i=0; i<cons.length; i++) {
			scores[i] = cons[i].fitness();
		}
		return scores;
	}
	
	public double average(int[] scores) {
		double avg=0;
		for (int s : scores) {
			avg+=s;
		}
		return avg/scores.length;
	}
}
